package com.example.gulimallserch.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.gulimallserch.config.GulimallEsConfig;
import com.example.gulimallserch.constant.EsConstant;
import com.example.gulimallserch.service.AddService;
import com.wu.common.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class AddServiceImpl implements AddService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> collect) {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : collect) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, GulimallEsConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (bulk.hasFailures()){
            List<String> collect1 = Arrays.stream(bulk.getItems()).map(x -> x.getId()).collect(Collectors.toList());
            return false;
        }
        return true;

    }
}
